﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.Skins;
using DevExpress.LookAndFeel;
using DevExpress.UserSkins;
using DevExpress.XtraBars;
using DevExpress.XtraBars.Ribbon;
using DevExpress.XtraBars.Helpers;
using CNotebook;
using CNotebook.Purchases;

namespace NotebookS2
{
    public partial class AcknowledgementReceipt : RibbonForm
    {
        public AcknowledgementReceipt()
        {
            InitializeComponent();
        }

        #region Properties
        public string ConnectionString { get; set; }
        public string ActiveUserID { get; set; }
        public bool IsMultipleWarehouse { get; set; }
        public string DefaultWarehouse { get; set; }

        public DataTable PurchaseOderLineItems { get; set; }
        public string DefaultPriceList { get; set; }
        public string DefaultCurrency { get; set; }
        public string VATCode { get; set; }
        public string VATRate { get; set; }
        public bool IsInclusive { get; set; }
        public double WithHoldingTaxRate { get; set; }

        //txtCode

        
        private string _CardCode;

        public string CardCode
        {
            get { return _CardCode; }
            set { _CardCode = value; txtCardCode.Text = _CardCode; }
        }
        private string _CardName;

        public string CardName
        {
            get { return _CardName; }
            set { _CardName = value; txtCardName.Text = _CardName; }
        }

        string _Department;
        public string Department
        {
            get { return _Department; }
            set { _Department = value; cboDepartment.Text = _Department; }
        }
        string _Division;
        public string Division
        {
            get { return _Division; }
            set { _Division = value; cboDivision.Text = _Division; }
        }
        string _RequestedBy;
        public string RequestedBy
        {
            get { return _RequestedBy; }
            set { _RequestedBy = value; txtRequestBy.Text = _RequestedBy; }
        }

        private string _ContactPerson;

        public string ContactPerson
        {
            get { return _ContactPerson; }
            set { _ContactPerson = value; txtContactPerson.Text = _ContactPerson; }
        }
        private string _Reference;

        public string Reference
        {
            get { return _Reference; }
            set { _Reference = value; txtReference.Text = _Reference; txtReference.Properties.ReadOnly = true; }
        }
        private string _BillTo;

        public string BillTo
        {
            get { return _BillTo; }
            set { _BillTo = value; txtBillTo.Text = _BillTo; }
        }
        private string _ShipTo;

        public string ShipTo
        {
            get { return _ShipTo; }
            set { _ShipTo = value; txtShipTo.Text = _ShipTo; }
        }
        private DateTime _PostingDate;

        public DateTime PostingDate
        {
            get { return _PostingDate; }
            set { _PostingDate = value; dtPostDate.EditValue = _PostingDate; }
        }
        private DateTime _DeliveryDate;

        public DateTime DeliveryDate
        {
            get { return _DeliveryDate; }
            set { _DeliveryDate = value; dtDeliveryDate.EditValue = _DeliveryDate; }
        }
        private DateTime _DocumentDate;

        public DateTime DocumentDate
        {
            get { return _DocumentDate; }
            set { _DocumentDate = value; dtDocDate.EditValue = _DocumentDate; }
        }

        private string _Remarks;

        public string Remarks
        {
            get { return _Remarks; }
            set { _Remarks = value; txtRemarks.Text = _Remarks; }
        }
        private string _GrossAmount;

        public string GrossAmount
        {
            get { return _GrossAmount; }
            set { _GrossAmount = value; txtGrossAmount.Text = _GrossAmount; }
        }
       
        private string _VAT;

        public string VAT
        {
            get { return _VAT; }
            set { _VAT = value; txtVAT.Text = _VAT; }
        }
        private string _NetAmount;

        public string NetAmount
        {
            get { return _NetAmount; }
            set { _NetAmount = value; txtNetAmt.Text = _NetAmount; }
        }



        #endregion

        #region Initialization

        public void BindEntities()
        {
            EntityManager oManager = new EntityManager();
            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();
            DataTable oTable = new DataTable();

            oTable = oManager.GetEntities();

            cboEntities.Visible = false;
            cboEntities.Properties.DataSource = oTable;
            cboEntities.Properties.DisplayMember = "EntityDescription";
            cboEntities.Properties.ValueMember = "EntityDescription";
            DevExpress.XtraEditors.Controls.LookUpColumnInfo col;

            col = new DevExpress.XtraEditors.Controls.LookUpColumnInfo("EntityDescription", "EntityDescription", 100);

            col.SortOrder = DevExpress.Data.ColumnSortOrder.Ascending;
            cboEntities.Properties.Columns.Clear();
            cboEntities.Properties.Columns.Add(col);
            cboEntities.Properties.ShowHeader = false;
            cboEntities.Visible = true;
            oManager.Close();
        }

        public void GetBusinessPartnerDefaults(string sCardCode)
        {
            #region Getting the Default Setup of Customer in BP Master File
            AddressBookManager oBPManager = new AddressBookManager();

            oBPManager.ConnectionString = this.ConnectionString;
            oBPManager.Open();

            this.DefaultPriceList = oBPManager.GetPriceListCode(sCardCode);
            this.WithHoldingTaxRate = oBPManager.GetWithHoldingTaxRate(sCardCode);

            oBPManager.Close();
            #endregion


            //dtDeliveryDate.EditValue = ((DateTime)dtPostDate.EditValue).AddDays(Convert.ToInt16(txtPaymentTerms.Text));

            #region Getting the Tax Code Setup
            TaxManager oTxManager = new TaxManager();

            oTxManager.ConnectionString = this.ConnectionString;
            oTxManager.Open();

            this.VATRate = oTxManager.GetVATRate(this.VATCode).ToString();
            this.IsInclusive = oTxManager.IsInclusive(this.VATCode) == "Y" ? true : false;

            #endregion


        }
        public DataTable GetTable()
        {
            DataTable table = new DataTable();

            table.Columns.Add("Particulars", typeof(string));
            table.Columns.Add("AcctCode", typeof(string));
            table.Columns.Add("AcctName", typeof(string));
            table.Columns.Add("Amount", typeof(double));
            table.Columns.Add("ItemGuid", typeof(string));
            return table;

        }

        void InitializeSeries()
        {

            string _ACKNOWLEDGEMENT_RECEIPT_SERIES = this.ObjectType.ToString();
            SeriesManager oSeries = new SeriesManager();
            oSeries.ConnectionString = this.ConnectionString;
            oSeries.Open();

            lblValidUntilDeliveryDate.Text = "Date Needed:";
            if (oSeries.IsAutoNumber(_ACKNOWLEDGEMENT_RECEIPT_SERIES) == true)
            {
                txtDocumentNumber.Properties.ReadOnly = true;
                txtDocumentNumber.Text = "##########";

            }
            oSeries.Close();
 
        }
        
        #endregion

        #region Functions


        public void BindDepartment()
        {
            DepartmentManager oManager = new DepartmentManager();

            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();

            cboDepartment.Properties.Columns.Add(new DevExpress.XtraEditors.Controls.LookUpColumnInfo("DeptName"));
            cboDepartment.Properties.DisplayMember = "DeptName";
            cboDepartment.Properties.ValueMember = "DeptName";

            cboDepartment.Properties.DataSource = oManager.GetDepartment();
            cboDepartment.Properties.ShowHeader = false;
            cboDepartment.Refresh();

            oManager.Close();
        }

        public void BindDivision()
        {
            CardDivisionManager oManager = new CardDivisionManager();

            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();

            cboDivision.Properties.Columns.Add(new DevExpress.XtraEditors.Controls.LookUpColumnInfo("DivName"));
            cboDivision.Properties.DisplayMember = "DivName";
            cboDivision.Properties.ValueMember = "DivName";

            cboDivision.Properties.DataSource = oManager.GetDivision();
            cboDivision.Properties.ShowHeader = false;
            cboDivision.Refresh();

            oManager.Close();
        }
        
        public void PrintPreview()
        {
            PRNT_RCPT_SVC oPrint = new PRNT_RCPT_SVC();
            oPrint.DocumentStatus = txtStatus.Text;

            if (txtStatus.Text == "Draft")
            {
                oPrint.ConnectionString = this.ConnectionString;
                oPrint.DocumentNumber = txtDocumentNumber.Text;
                oPrint.DocumentStatus = "Draft";

                oPrint.WindowState = FormWindowState.Maximized;
                oPrint.ShowDialog();
            }
            else if (txtStatus.Text == "Posted")
            {
                    oPrint.ConnectionString = this.ConnectionString;
                    oPrint.DocumentNumber = txtDocumentNumber.Text;

                    oPrint.WindowState = FormWindowState.Maximized;
            
                    oPrint.ShowDialog();
            }
            else if (txtStatus.Text == "Printed" || txtStatus.Text == "Open" || txtStatus.Text == "Closed")
            {
                oPrint.ConnectionString = this.ConnectionString;
                oPrint.DocumentNumber = txtDocumentNumber.Text;
                oPrint.DocumentStatus = txtStatus.Text;
                oPrint.WindowState = FormWindowState.Maximized;
                oPrint.ShowDialog();
            }
        }

        void EnableControls()
        {
            txtInvoiceDR.Enabled = true;
            cboDepartment.Enabled = true;
            cboDivision.Enabled = true;
            cboEntities.Enabled = true;

            txtCardCode.Enabled = true;
            txtCardName.Enabled = true;
            txtContactPerson.Enabled = true;
            txtReference.Enabled = true;
            txtBillTo.Enabled = true;
            txtShipTo.Enabled = true;
            txtDocumentNumber.Enabled = true;
            dtPostDate.Enabled = true;
            dtDeliveryDate.Enabled = true;
            dtDocDate.Enabled = true;
            
            
            txtRemarks.Enabled = true;
            txtGrossAmount.Enabled = true;
            
            txtVAT.Enabled = true;
            txtNetAmt.Enabled = true;

            btnAdd.Enabled = true;

            foreach (DevExpress.XtraGrid.Columns.GridColumn oColumn in gridView1.Columns)
            {
                if (oColumn.Name == "Code" || oColumn.Name == "Quantity" || oColumn.Name == "Free")
                {
                    oColumn.OptionsColumn.AllowEdit = true;
                }
            }

        }

        void DisableControls()
        {

            txtInvoiceDR.Enabled = false;
            cboEntities.Enabled = false;
            cboDepartment.Enabled = false;
            cboDivision.Enabled = false;
            txtCardCode.Enabled = false;
            txtCardName.Enabled = false;
            txtContactPerson.Enabled = false;
            txtReference.Enabled = false;
            txtBillTo.Enabled = false;
            txtShipTo.Enabled = false;
            txtDocumentNumber.Enabled = false;
            dtPostDate.Enabled = false;
            dtDeliveryDate.Enabled = false;
            dtDocDate.Enabled = false;
            
            
            txtRemarks.Enabled = false;
            txtGrossAmount.Enabled = false;
            txtVAT.Enabled = false;
            txtNetAmt.Enabled = false;

            btnAdd.Enabled = false;
            foreach (DevExpress.XtraGrid.Columns.GridColumn oColumn in gridView1.Columns)
            {
                oColumn.OptionsColumn.AllowEdit = false;
            }
            
        }

        string GetNewSeries()
        {
            string _SERIES = "";
            string _DOCTYPE = this.ObjectType.ToString();

            SeriesManager oSeries = new SeriesManager();
            oSeries.ConnectionString = this.ConnectionString;
            oSeries.Open();
            if (oSeries.IsAutoNumber(_DOCTYPE) == true)
            {
                _SERIES = oSeries.GetNewSeries(_DOCTYPE);
            }
            else
            {
                _SERIES = txtDocumentNumber.Text;
            }
            oSeries.Close();

            return _SERIES;
        }

        void ComputeTotal()
        {
            try
            {
                double _GrossAmount = 0;
                double _NetAmount = 0;
                double _WithHoldingTax = 0;
              
                double _VAT = 0;

                foreach (DataRow oRow in this.PurchaseOderLineItems.Rows)
                {
                    if (oRow["Amount"] != DBNull.Value)
                    {
                        _GrossAmount = _GrossAmount + (Convert.ToDouble(oRow["Amount"]));
                      
                    }
                }

                _NetAmount = _GrossAmount;
                if (this.VATCode != "NON-VAT")
                {
                    if (this.IsInclusive == true)
                    {
                        
                        _VAT = _NetAmount - (_NetAmount  / Convert.ToDouble(this.VATRate));
                        _VAT = Convert.ToDouble(_VAT.ToString("##.00"));
                        txtVAT.Text = _VAT.ToString();
                        _WithHoldingTax = ((_NetAmount / Convert.ToDouble(this.VATRate)) * (this.WithHoldingTaxRate / 100));

                        txtWithHoldingTax.Text = _WithHoldingTax.ToString("#,###.00");
                        
                    }
                    else
                    {
                        txtVAT.Text = "0";
                    }
                }
                else
                {
                    txtWithHoldingTax.Text = Convert.ToString((_NetAmount * (this.WithHoldingTaxRate / 100)).ToString("##.00"));
                }

                txtGrossAmount.Text = _GrossAmount.ToString("#,###.00");
                _NetAmount = _NetAmount - _WithHoldingTax;
                
                txtNetAmt.Text = _NetAmount.ToString("#,###.00");

            }
            catch
            {
            }

        }
        
        void RemoveBlankLastRowFirst()
        {
            
            gridView1.MoveLast();

            string sItemCode = "";


            sItemCode = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["AcctCode"]).ToString();

            if (sItemCode.Trim() == "")
            {
                gridView1.DeleteRow(gridView1.FocusedRowHandle);
            }


        }

        public void ShowSearch()
        {
            FND_RCPT_SVC oSearchDocument = new FND_RCPT_SVC();

            oSearchDocument.ConnectionString = this.ConnectionString;
            oSearchDocument.ShowDialog();

            string sDocumentNumber = oSearchDocument.DocumentNumber;


            if (sDocumentNumber != null || sDocumentNumber.Trim() != "")
            {
                ServiceReceiptManager oManager = new ServiceReceiptManager();

                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                DataRow oRow = oManager.GetPurchaseOrder(sDocumentNumber);

                txtDocumentNumber.Enabled = false;
                #region Header 
                txtDocumentNumber.Text = oRow["DocNum"].ToString();
                txtStatus.Text = oRow["DocStatus"].ToString();
                dtPostDate.EditValue = (DateTime)oRow["PostingDate"];
                dtDeliveryDate.EditValue = (DateTime)oRow["DueDate"];
                dtDocDate.EditValue = (DateTime)oRow["DocDate"];

                cboEntities.Properties.SearchMode = DevExpress.XtraEditors.Controls.SearchMode.AutoComplete;
                if (oRow["EntityCode"] == DBNull.Value)
                {
                    cboEntities.EditValue = null;
                }
                else
                {
                    cboEntities.Text = oRow["EntityCode"].ToString();
                }

                txtCardCode.EditValue = oRow["CardCode"].ToString();
                AddressBookManager oCardManager = new AddressBookManager();
                oCardManager.Connection = oManager.Connection;
                this.DefaultPriceList = oCardManager.GetPriceListCode(txtCardCode.Text);
                txtCardName.EditValue = oRow["CardName"].ToString();
                txtContactPerson.EditValue = oRow["ContactPerson"].ToString();
                txtReference.EditValue = oRow["Reference"].ToString();
                if (oRow["InvDRNo"] != DBNull.Value)
                {
                    txtInvoiceDR.Text = oRow["InvDRNo"].ToString();
                }
                txtBillTo.EditValue = oRow["BillTo"].ToString();
                txtShipTo.EditValue = oRow["ShipTo"].ToString();
                
                txtRequestBy.EditValue = oRow["RequestedBy"].ToString();
                cboDepartment.EditValue = oRow["Department"].ToString();
                cboDivision.EditValue = oRow["Division"].ToString();
                txtRemarks.EditValue = oRow["Remarks"].ToString();

                
                if (oRow["VATCode"] != DBNull.Value)
                {
                    this.VATCode = oRow["VATCode"].ToString();
                }

                this.VATRate = oRow["VATRate"].ToString();

                if (oRow["IsVATInclusive"] != DBNull.Value)
                {

                    if (oRow["IsVATInclusive"].ToString() == "Y")
                    {
                        this.IsInclusive = true;
                    }
                    else
                    {
                        this.IsInclusive = false;
                    }
                }

                txtGrossAmount.EditValue = oRow["GrossAmount"].ToString();
                txtVAT.EditValue = oRow["VATAmount"].ToString();
                txtNetAmt.EditValue = oRow["NetAmount"].ToString();

                GetBusinessPartnerDefaults(txtCardCode.Text);

                #endregion

                #region Line Items
                this.PurchaseOderLineItems = oManager.GetPOLineItems(sDocumentNumber);
                gridControl1.DataSource = this.PurchaseOderLineItems;
                gridControl1.Refresh();

                if (txtStatus.Text == "Draft")
                {
                    if (gridView1.RowCount <= 0)
                    {
                        gridView1.AddNewRow();
                    }
                }

                #endregion

                oManager.Close();

                btnAdd.Text = "Update";

                ComputeTotal();
                
            }

          
        }

        void CancelOrder(string sDocNumber)
        {
            if (MessageBox.Show("Are you sure you want to cancel this document?", "Cancel", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                ServiceReceiptManager oManager = new ServiceReceiptManager();

                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                oManager.CancelDocument(sDocNumber);
                oManager.Close();

                txtStatus.Text = "Canceled";
            }

        }


        void ChangePrintStatus(string sDocNumber)
        {
            ServiceReceiptManager oManager = new ServiceReceiptManager();

            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();
            oManager.ChangePrintStatus(sDocNumber);
            oManager.Close();

            txtStatus.Text = "Printed";
            

        }

        void PostRequest(string sDocNumber)
        {
            if (MessageBox.Show("Are you sure you want to post this document?", "Cancel", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                ServiceReceiptManager oManager = new ServiceReceiptManager();

                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                oManager.PostDocument(sDocNumber);
                oManager.Close();

                txtStatus.Text = "Posted";
               
            }
        }

        void CloseRequest(string sDocNumber)
        {
            if (MessageBox.Show("Are you sure you want to close this document?", "Cancel", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                ServiceReceiptManager oManager = new ServiceReceiptManager();

                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                oManager.CloseDocument(sDocNumber);
                oManager.Close();

                txtStatus.Text = "Closed";
               
            }
        }
        #endregion

        public int ObjectType { get { return 20; } }
        

        string ApplyAuthorization()
        {
            UserManager oManager = new UserManager();

            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();

            string iAccessType = oManager.GetAccessType(this.ObjectType, this.ActiveUserID);

            oManager.Close();

            switch (iAccessType)
            {
                case "Full Access":
                    FullAccess();
                    break;
                case "Read Only":
                    ApplyReadOnly();
                    break;
                case "No Access":
                    NoAccess();
                    break;
            }

            return iAccessType;
        }


        int ApplyReadOnly()
        {
            DisableControls();

            txtStatus.Properties.Buttons[0].Enabled = false;
            txtStatus.Properties.Buttons[1].Enabled = false;


            return 2;
        }

        int FullAccess()
        {
            txtStatus.Properties.Buttons[0].Enabled = true;
            txtStatus.Properties.Buttons[1].Enabled = true;

            return 1;
        }

        int NoAccess()
        {
            MessageBox.Show("You have no right to access this module!!!!", "Security Policy", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            return 3;

        }


        #region Form Events

        private void SalesOrder_Load(object sender, EventArgs e)
        {
            cboDocType.SelectedIndex = 1;
            BindDepartment();
            BindDivision();
            BindEntities();

            dtPostDate.EditValue = System.DateTime.Now;
            dtDeliveryDate.EditValue = System.DateTime.Now;
            dtDocDate.EditValue = System.DateTime.Now;

            
            if (this.PurchaseOderLineItems == null)
            {
                this.PurchaseOderLineItems = GetTable();
            }

            gridControl1.DataSource = this.PurchaseOderLineItems;
            gridControl1.Refresh();

            if (gridView1.DataRowCount <= 0)
            {
                gridView1.AddNewRow();
            }

            InitializeSeries();
            
        }

        private void gridView1_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                int iCount = gridView1.FocusedRowHandle;
                
                if (e.KeyCode == Keys.Delete)
                {
                    if (txtStatus.Text == "Draft")
                    {
                        if (MessageBox.Show("Are you sure you want to delete this Row?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {

                            if (gridView1.IsLastRow)
                            {
                                string _ACCOUNT_CODE = "";

                                _ACCOUNT_CODE = gridView1.GetRowCellValue(iCount, gridView1.Columns["AcctCode"]).ToString();


                                if (_ACCOUNT_CODE != "")
                                {
                                    gridView1.DeleteRow(iCount);
                                    gridView1.AddNewRow();
                                }

                                
                                gridView1.RefreshData();

                            }
                            else
                            {

                                string _ACCOUNT_CODE = "";


                                _ACCOUNT_CODE = gridView1.GetRowCellValue(iCount, gridView1.Columns["AcctCode"]).ToString();

                                if (_ACCOUNT_CODE != "")
                                {
                                    gridView1.DeleteRow(iCount);
                                }

                                gridView1.RefreshData();
                            }

                            ComputeTotal();
                        }
                    }
                }
                
                if (e.KeyCode == Keys.Down)
                {
                    if (gridView1.IsLastRow)
                    {
                        string _ACCOUNT_CODE = "";
                        
                        _ACCOUNT_CODE = gridView1.GetRowCellValue(iCount, gridView1.Columns["AcctCode"]).ToString();

                        if (_ACCOUNT_CODE != "" && (txtStatus.Text == "Draft") && txtReference.Text == "")
                        {
                            gridView1.AddNewRow();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }        

        bool InComplete()
        {
            bool _Incomplete = false;

            if (txtDocumentNumber.Text == "") { return true; }
            if (txtCardCode.Text == "") { return true; }
            if (txtCardName.Text == "") { return true; }


          

            foreach (DataRow oRow in this.PurchaseOderLineItems.Rows)
            {
                double _AMOUNT = Convert.ToDouble(oRow["Amount"]);

                if (_AMOUNT == 0)
                {
                    return true;
                }
            }

            return _Incomplete;

        }
        private void btnAdd_Click(object sender, EventArgs e)
        {
            ServiceReceiptManager oManager = new ServiceReceiptManager();
            ServiceReceiptUnit oUnit = new ServiceReceiptUnit();
            RemoveBlankLastRowFirst();
            if (InComplete() == false)
            {
                
                if (btnAdd.Text != "Update")
                {
                    #region Header Sales Quote

                    txtDocumentNumber.Text = GetNewSeries();
                    oUnit.DocumentNumber = txtDocumentNumber.Text;
                    oUnit.DocumentStatus = txtStatus.Text;
                    oUnit.PostingDate = (DateTime)dtPostDate.EditValue;
                    oUnit.DueDate = (DateTime)dtDeliveryDate.EditValue;
                    oUnit.DocDate = (DateTime)dtDocDate.EditValue;

                    
                    oUnit.CardCode = txtCardCode.Text;
                    oUnit.CardName = txtCardName.Text;
                    oUnit.ContactPerson = txtContactPerson.Text;
                    oUnit.Reference = txtReference.Text;
                    oUnit.InvoiceDRNo = txtInvoiceDR.Text;
                    oUnit.ShipTo = txtShipTo.Text;
                    oUnit.BillTo = txtBillTo.Text;

                    oUnit.Department = cboDepartment.Text;
                    oUnit.EntityCode = cboEntities.Text;
                    oUnit.Division = cboDivision.Text;
                    oUnit.RequestedBy = txtRequestBy.Text;
                    oUnit.Remarks = txtRemarks.Text;

                    oUnit.TaxCode = this.VATCode.ToString();
                    oUnit.TaxRate = Convert.ToDouble(this.VATRate.ToString());

                    if (oUnit.TaxCode != "NON-VAT")
                    {
                        oUnit.IsVATInclusive = this.IsInclusive == true ? "Y" : "N";
                    }
                    else
                    {
                        oUnit.IsVATInclusive = "N/A";
                    }

                    oUnit.GrossAmnt = Convert.ToDouble(txtGrossAmount.Text.Replace(",", "").ToString());
                    oUnit.VATAmt = Convert.ToDouble(txtVAT.Text.Replace(",", "").ToString());
                   
                    oUnit.WithHoldingTax = Convert.ToDouble(txtWithHoldingTax.Text);
                    oUnit.NetAmount = Convert.ToDouble(txtNetAmt.Text.Replace(",", "").ToString());

                    #endregion

                    oUnit.LineItems = this.PurchaseOderLineItems;

                    oManager.ConnectionString = this.ConnectionString;
                    oManager.Open();

                    if (oManager.IsDocumentExists(txtDocumentNumber.Text) == false)
                    {
                        #region Adding Part
                        oManager.AddPurchaseOrder(oUnit);
                        btnAdd.Text = "Update";
                        #endregion

                        MessageBox.Show("Saving document is successful!!!", "Sales Order", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        txtDocumentNumber.Enabled = false;
                    }
                    else
                    {
                        MessageBox.Show("Document already exists in the Database!!!", "Sales Order", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }

                    oManager.Close();
                    
                    
                }
                else
                {

                    #region Header Sales Quote

                    oUnit.DocumentNumber = txtDocumentNumber.Text;
                    oUnit.DocumentStatus = txtStatus.Text;
                    oUnit.PostingDate = (DateTime)dtPostDate.EditValue;
                    oUnit.DueDate = (DateTime)dtDeliveryDate.EditValue;
                    oUnit.DocDate = (DateTime)dtDocDate.EditValue;

                    oUnit.CardCode = txtCardCode.Text;
                    oUnit.CardName = txtCardName.Text;
                    oUnit.ContactPerson = txtContactPerson.Text;
                    oUnit.Reference = txtReference.Text;
                    oUnit.InvoiceDRNo = txtInvoiceDR.Text;
                    oUnit.ShipTo = txtShipTo.Text;
                    oUnit.BillTo = txtBillTo.Text;

                    
                    oUnit.WithHoldingTax = Convert.ToDouble(txtWithHoldingTax.Text);

                    oUnit.EntityCode = cboEntities.Text;
                    oUnit.Department = cboDepartment.Text;
                    oUnit.Division = cboDivision.Text;
                    oUnit.RequestedBy = txtRequestBy.Text;
                    oUnit.Remarks = txtRemarks.Text;

                    oUnit.TaxCode = this.VATCode.ToString();
                    oUnit.TaxRate = Convert.ToDouble(this.VATRate.ToString());
                    if (oUnit.TaxCode != "NON-VAT")
                    {
                        oUnit.IsVATInclusive = this.IsInclusive == true ? "Y" : "N";
                    }
                    else
                    {
                        oUnit.IsVATInclusive = "N/A";
                    }



                    oUnit.GrossAmnt = Convert.ToDouble(txtGrossAmount.Text.Replace(",", "").ToString());
                    oUnit.VATAmt = Convert.ToDouble(txtVAT.Text.Replace(",", "").ToString());
                    
                    oUnit.NetAmount = Convert.ToDouble(txtNetAmt.Text.Replace(",", "").ToString());

                    #endregion

                    oUnit.LineItems = this.PurchaseOderLineItems;

                    #region Updating Portion
                    oManager.ConnectionString = this.ConnectionString;
                    oManager.Open();
                    oManager.UpdatePurchaseOrder(oUnit);
                    oManager.Close();
                    #endregion

                    MessageBox.Show("Updating document is successful!!!", "Sales Order", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            else
            {
                MessageBox.Show("Please complete the required information, zero value in the quantity is also not allowed in the Line Items!!!", "Sales Order", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

        }

        
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void txtQty_Leave(object sender, EventArgs e)
        {
            try
            {
                ComputeTotal();
            }
            catch
            {
            }
        }

        private void gridView1_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
            ComputeTotal();
        }

        
        #endregion

        private void txtStatus_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (txtDocumentNumber.Text != "##########" )
            {
                if (txtStatus.Text == "Draft")
                {
                    if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.OK)
                    {
                        PostRequest(txtDocumentNumber.Text);
                    }

                    if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Close)
                    {
                        CancelOrder(txtDocumentNumber.Text);
                    }
                }
                else
                {
                    if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Close)
                    {
                        CloseRequest(txtDocumentNumber.Text);
                    }
                }
            }
            
        }

        private void txtStatus_EditValueChanged(object sender, EventArgs e)
        {
            if (txtStatus.Text == "Draft")
            {
                txtStatus.Properties.Buttons[0].Visible = true;
                txtStatus.Properties.Buttons[1].Visible = true;
                EnableControls();
            }
            if (txtStatus.Text == "Canceled" || txtStatus.Text == "Closed" || txtStatus.Text == "Printed")
            {
                txtStatus.Properties.Buttons[0].Visible = false;
                txtStatus.Properties.Buttons[1].Visible = false;
                DisableControls();
            }

            if (txtStatus.Text == "Posted")
            {
                txtStatus.Properties.Buttons[0].Visible = false;
                txtStatus.Properties.Buttons[1].Visible = true;
                DisableControls();
            }

            if (txtStatus.Text == "Open")
            {
                txtStatus.Properties.Buttons[0].Visible = false;
                txtStatus.Properties.Buttons[1].Visible = true;
                DisableControls();
            }
        }

      

        private void txtReference_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            FND_POSVC _SEARCH_REFERENCE_RQST = new FND_POSVC();

            
            if (txtCardCode.Text != "")
            {
                _SEARCH_REFERENCE_RQST.ConnectionString = this.ConnectionString;
                //_SEARCH_REFERENCE_RQST.CardCode = txtCardCode.Text;

                _SEARCH_REFERENCE_RQST.ShowDialog();
                txtReference.Text = _SEARCH_REFERENCE_RQST.DocumentNumber;

                if (txtReference.Text != "")
                {
                    PurchaseOrderSVCManager oManager = new PurchaseOrderSVCManager();

                    oManager.ConnectionString = this.ConnectionString;
                    oManager.Open();

                    
                    DataTable dt = oManager.GetPostedPO(txtReference.Text);

                    DataRow _HEADERRow = dt.Rows[0];

                    txtRequestBy.Text = _HEADERRow["CardName"].ToString();
                    cboDepartment.Text = _HEADERRow["Department"].ToString();
                    cboDepartment.ClosePopup();
                    cboDivision.Text = _HEADERRow["Division"].ToString();
                    cboDivision.ClosePopup();


                    DataTable dtLineItems = oManager.GetPOLineItems(txtReference.Text);


                    if (dtLineItems.Rows.Count > 0)
                    {
                        this.PurchaseOderLineItems = dtLineItems;

                        gridControl1.DataSource = this.PurchaseOderLineItems;
                        gridControl1.Refresh();
                        oManager.Close();
                    }

                    ComputeTotal();
                }


            }
            else { MessageBox.Show("Please select customer first!!!", "Card Code", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); }
        }

        private void PurchaseOrder_Shown(object sender, EventArgs e)
        {
            cboDivision.Text = this.Division;
            cboDepartment.Text = this.Department;
            gridControl1.Select();
            gridView1.FocusedRowHandle = DevExpress.XtraGrid.GridControl.NewItemRowHandle;
            gridView1.FocusedColumn = gridView1.Columns["Particulars"];
            gridView1.ShowEditor();

            txtCardCode.Focus();

            string _USR_AUTHORIZATION = ApplyAuthorization();
            if (_USR_AUTHORIZATION == "No Access")
            {
                btnCancel_Click(sender, e);
            }
        }

        private void gridView1_CustomColumnDisplayText(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventArgs e)
        {
            if (e.Column.FieldName == "")

                e.DisplayText = (e.RowHandle + 1).ToString();
        }

        private void txtCardCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                AddressBookManager oManager = new AddressBookManager();
                TaxManager oTxManager = new TaxManager();
                DataTable _TABLE = new DataTable();

                try
                {

                    oManager.ConnectionString = this.ConnectionString;
                    oManager.Open();

                    _TABLE = oManager.GetByBPCode(txtCardCode.Text, "Vendor");

                    oManager.Close();

                    int iCount = _TABLE.Rows.Count;

                    if (iCount == 0)
                    {
                        #region if no data return during enter
                        FND_BP _SearchBP = new FND_BP();

                        AddressBookManager oBPManager = new AddressBookManager();

                        try
                        {
                            _SearchBP.ConnectionString = this.ConnectionString;
                            _SearchBP.BusinessPartnerType = "Vendor";
                            _SearchBP.SetSearchByBPCode(txtCardCode.Text);

                            _SearchBP.ShowDialog();

                            txtCardCode.Text = _SearchBP.CardCode;
                            txtCardName.Text = _SearchBP.CardName;
                            txtBillTo.Text = _SearchBP.Address;

                            this.WithHoldingTaxRate = _SearchBP.WithHoldingTax;
                            txtContactPerson.Text = _SearchBP.ContactPerson;
                            this.DefaultPriceList = _SearchBP.PriceList;
                            this.VATCode = _SearchBP.VATCode;
                            

                            oTxManager.ConnectionString = this.ConnectionString;
                            oTxManager.Open();


                            this.VATRate = oTxManager.GetVATRate(this.VATCode).ToString();

                            this.IsInclusive = oTxManager.IsInclusive(this.VATCode) == "Y" ? true : false;



                            oTxManager.Close();

                            //if (_SearchBP.BuyerSalesMan != "")
                            //{
                            //    cboSalesman.EditValue = _SearchBP.BuyerSalesMan;
                            //}

                            _SearchBP.Dispose();
                        }
                        catch
                        {
                        }
                        #endregion
                        return;
                    }

                    DataRow oRow = _TABLE.Rows[0];


                    this.WithHoldingTaxRate = Convert.ToDouble(oRow["WithHoldingTax"]);
                    txtCardCode.Text = oRow["BPCode"].ToString();
                    txtCardName.Text = oRow["BPName"].ToString();
                    txtBillTo.Text = oRow["Address"].ToString();
                    //txtPaymentTerms.Text = oRow["PaymentTerm"].ToString();
                    txtContactPerson.Text = oRow["ContactPerson"].ToString(); ;
                    this.DefaultPriceList = oRow["PriceList"].ToString(); ;
                    this.VATCode = oRow["VATCode"].ToString();
                  

                    //cboCurrency.Text 
                    oTxManager.ConnectionString = this.ConnectionString;
                    oTxManager.Open();


                    this.VATRate = oTxManager.GetVATRate(this.VATCode).ToString();

                    this.IsInclusive = oTxManager.IsInclusive(this.VATCode) == "Y" ? true : false;


                    oTxManager.Close();

                    //if (oRow["SMCODE"].ToString() != "")
                    //{
                    //    cboSalesman.EditValue = oRow["SMCODE"].ToString();
                    //}
                }
                catch
                {
                }
            }
        }

        private void txtCardCode_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            FND_BP _SearchBP = new FND_BP();

            AddressBookManager oBPManager = new AddressBookManager();
            TaxManager oTxManager = new TaxManager();

            try
            {
                _SearchBP.ConnectionString = this.ConnectionString;
                _SearchBP.BusinessPartnerType = "Vendor";
                _SearchBP.ShowDialog();


                this.WithHoldingTaxRate = _SearchBP.WithHoldingTax;
                txtCardCode.Text = _SearchBP.CardCode;
                txtCardName.Text = _SearchBP.CardName;
                txtBillTo.Text = _SearchBP.Address;
                txtContactPerson.Text = _SearchBP.ContactPerson;
                this.DefaultPriceList = _SearchBP.PriceList;
                this.VATCode = _SearchBP.VATCode;

                oTxManager.ConnectionString = this.ConnectionString;
                oTxManager.Open();


                this.VATRate = oTxManager.GetVATRate(this.VATCode).ToString();

                this.IsInclusive = oTxManager.IsInclusive(this.VATCode) == "Y" ? true : false;

                oTxManager.Close();


                _SearchBP.Dispose();

                ComputeTotal();
                
            }
            catch
            {
            }
        }

        private void btnSearchAcctCode_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            FND_GLACCOUNT oForm = new FND_GLACCOUNT();

            oForm.ConnectionString = this.ConnectionString;

            oForm.ShowDialog();

            gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["AcctCode"], oForm.SelectedGLAcctCode);
            gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["AcctName"], oForm.SelectedGLAcctName);

        }


        private void xtraScrollableControl1_Click(object sender, EventArgs e)
        {

        }

        private void cboDocType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cboDocType.SelectedIndex != 1)
            {
                PurchaseOrder oForm = new PurchaseOrder();

                oForm.ConnectionString = this.ConnectionString;
                oForm.ActiveUserID = this.ActiveUserID;
                oForm.IsMultipleWarehouse = this.IsMultipleWarehouse;
                oForm.DefaultWarehouse = this.DefaultWarehouse;
                oForm.MdiParent = this.MdiParent;
                oForm.Show();
                this.Close();
            }
        }

        private void ribbonControl1_Click(object sender, EventArgs e)
        {

        }

    }
}
